package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class SpinLockPrintABCService {

    private final AtomicInteger state = new AtomicInteger(0);  // 状态值：0 - A, 1 - B, 2 - C
    private static final int TOTAL_CYCLES = 5;  // 总共循环次数

    public void printABCSequence() {
        Thread threadA = new Thread(this::printA);
        Thread threadB = new Thread(this::printB);
        Thread threadC = new Thread(this::printC);

        threadA.start();
        threadB.start();
        threadC.start();

        try {
            threadA.join();
            threadB.join();
            threadC.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("主线程被中断", e);
        }

        log.info("所有循环已完成，任务结束");
    }

    private void printA() {
        for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
            for (int i = 0; i < 3; i++) {  // 打印3次A
                while (state.get() != 0) {
                    // 自旋等待直到state为0
                }
                log.info("A");
                state.set(1);  // 设置状态为1，表示B可以执行
            }
        }
    }

    private void printB() {
        for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
            for (int i = 0; i < 2; i++) {  // 打印2次B
                while (state.get() != 1) {
                    // 自旋等待直到state为1
                }
                log.info("B");
                state.set(2);  // 设置状态为2，表示C可以执行
            }
        }
    }

    private void printC() {
        for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
            while (state.get() != 2) {
                // 自旋等待直到state为2
            }
            log.info("C");
            state.set(0);  // 设置状态为0，准备下一轮循环从A开始
        }
    }
}
